/**
 * MonacoIntegration for ArenaNext userscript.
 * Handles integration with the Monaco editor including registering editor actions,
 * setting up custom code lenses, and configuring the editor for JS development.
 *
 * This is the main entry point that imports from the monaco module.
 *
 * @module MonacoIntegration
 */

import {
  // Editor actions
  registerEditorActions,
  setupAutoFormatOnEnter,
  registerQuickFixProvider,

  // Language services
  registerColorProviders,
  setupJavaScriptOptions,
  setupCustomJavaScriptTheme,

  // Code lens
  registerCodeLensProvider,

  // Error decorations
  setupErrorDecorations,

  // Virtual file system
  updateVirtualFileSystem,

  // TypeScript options
  setupTypeScriptStrictnessOptions,

  // Utilities
  showNotification,

  // Inline completions
  registerMonacoInlineCompletionProvider,
} from "../monaco";

// Re-export all functionality
export {
  registerEditorActions,
  setupAutoFormatOnEnter,
  registerQuickFixProvider,
  registerColorProviders,
  setupJavaScriptOptions,
  setupCustomJavaScriptTheme,
  registerCodeLensProvider,
  setupErrorDecorations,
  updateVirtualFileSystem,
  setupTypeScriptStrictnessOptions,
  showNotification,
  registerMonacoInlineCompletionProvider,
};

/**
 * 设置自定义保存命令，拦截默认的保存快捷键并格式化代码
 * @param {Object} monacoController - Monaco控制器实例
 */
export function setupCustomSaveCommand(monacoController) {
  const monaco = monacoController.monacoController.monaco;
  const editor = monaco.editor.getEditors()[0];

  // 添加自定义保存命令
  editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => {
    // 格式化当前文档
    editor.getAction("editor.action.formatDocument").run();

    // 阻止默认的浏览器保存行为
    return true;
  });

  // 添加全局键盘事件监听器以拦截保存快捷键
  window.addEventListener(
    "keydown",
    (e) => {
      // 检测 Ctrl+S 或 Command+S
      if ((e.ctrlKey || e.metaKey) && e.key === "s") {
        e.preventDefault();
        e.stopPropagation();

        // 触发Monaco编辑器格式化操作
        editor.getAction("editor.action.formatDocument").run();

        return false;
      }
    },
    true
  );
}

/**
 * 设置F5键运行地图快捷键
 * @param {Object} monacoController - Monaco控制器实例
 */
export function setupRunShortcut(monacoController) {
  // 添加全局键盘事件监听器以拦截F5键
  window.addEventListener(
    "keydown",
    (e) => {
      // 检测 F5 键
      if (e.key === "F5") {
        e.preventDefault();
        e.stopPropagation();

        // 运行地图
        if (unsafeWindow.box3EditCore && unsafeWindow.box3EditCore.replica) {
          unsafeWindow.box3EditCore.replica.startProject();
        }

        return false;
      }
    },
    true
  );
}
